package com.eet.excel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.eet.excel.model.OrderModel;
import com.eet.excel.model.SelectRequest;
import com.eet.excel.repository.OrderRepository;
import com.eet.excel.service.ExportService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 动态导出Excel
 *
 * @author Administrator
 */
@Slf4j
@Service
@AllArgsConstructor
public class ExportServiceImpl implements ExportService {
    private final OrderRepository orderRepository;

    @Override
    public boolean dynamicExport(HttpServletResponse response, SelectRequest selectRequest, List<OrderModel> data) {
        boolean flag = false;
        try {
            // 动态添加所有表头行集合
            List<List<String>> headList = new ArrayList<>();
            // 表头
            List<String> selectList = getHeadList(selectRequest);
            selectList.forEach(item -> {
                List<String> headTitle = new ArrayList<>();
                headTitle.add(item);
                headList.add(headTitle);
            });
            String fileName = String.valueOf(System.currentTimeMillis());
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

            // 将list转换成object
            List<List<Object>> listOut = getProductVoList(selectRequest, data);
            EasyExcel.write(response.getOutputStream()).head(headList).sheet("测试Sheet").doWrite(listOut);
            flag = true;
        } catch (Exception e) {
            log.error("导出失败，异常信息为：{}", e.getMessage());
        }
        return flag;
    }

    @Override
    public List<OrderModel> findAll() {
        return orderRepository.findAll();
    }

    /**
     * 获取表头标题
     *
     * @param selectRequest 选择列
     * @return 标题集合
     */
    private List<String> getHeadList(SelectRequest selectRequest) {
        if (Objects.isNull(selectRequest)) {
            throw new NullPointerException("请选择导出列");
        }
        List<String> headList = new ArrayList<>();
        if (selectRequest.isId()) {
            headList.add("ID");
        }
        if (selectRequest.isFlowNum()) {
            headList.add("流水号");
        }
        if (selectRequest.isOrderAmount()) {
            headList.add("订单数量");
        }
        if (selectRequest.isPrice()) {
            headList.add("价格");
        }
        if (selectRequest.isCreateTime()) {
            headList.add("创建时间");
        }
        if (selectRequest.isUpdateTime()) {
            headList.add("更新时间");
        }
        if (selectRequest.isDescription()) {
            headList.add("描述信息");
        }
        return headList;
    }

    /**
     * 查询结果转换
     *
     * @param data          数据源
     * @param selectRequest 选中行实体
     * @return 转换后的集合数据
     */
    private List<List<Object>> getProductVoList(SelectRequest selectRequest, List<OrderModel> data) {
        if (Objects.isNull(selectRequest) || CollectionUtils.isEmpty(data)) {
            throw new NullPointerException("表头或者表体数据为空!");
        }
        List<List<Object>> result = new ArrayList<>();
        data.forEach(body -> {
            List<Object> tableData = new ArrayList<>();
            if (selectRequest.isId()) {
                tableData.add(body.getId());
            }
            if (selectRequest.isFlowNum()) {
                tableData.add(body.getFlowNum());
            }
            if (selectRequest.isOrderAmount()) {
                tableData.add(body.getOrderAmount());
            }
            if (selectRequest.isPrice()) {
                tableData.add(body.getPrice());
            }
            if (selectRequest.isCreateTime()) {
                tableData.add(body.getCreateTime());
            }
            if (selectRequest.isUpdateTime()) {
                tableData.add(body.getUpdateTime());
            }
            if (selectRequest.isDescription()) {
                tableData.add(body.getDescription());
            }
            result.add(tableData);
        });
        return result;
    }
}
